package site.lanmushan.framework.query.util;

import site.lanmushan.framework.query.entity.TreeNode;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
public class TreeUtil {


    /**
     * @param nodeList
     * @return
     */
    public static <T extends TreeNode> List<T> listToTree(List<T> nodeList) {
        List<T> tree = new ArrayList<T>();
        for (T root : nodeList) {
            if (root.isRoot()) {
                tree.add(findChildren(root, nodeList));
            }
        }
        return tree;
    }

    public static <T extends TreeNode> List<T> sortedTree(List<T> nodeList, Comparator<? super T> comparator) {
        nodeList.sort(comparator);
        nodeList.forEach(it -> {
            if (it.getChildren() != null) {
                sortedTree(it.getChildren(), comparator);
            }
        });
        return nodeList;
    }

    /**
     * 递归查找子节点
     *
     * @param nodeList
     * @return
     */
    private static <T extends TreeNode> T findChildren(T root, List<T> nodeList) {

        for (T it : nodeList) {
            if (!it.isRoot() && root.isChildren(it)) {
                root.addChildren(findChildren(it, nodeList));
            }
        }
        return root;
    }

    public static <T extends TreeNode> List<T> filterTree(List<T> nodeList, Predicate<? super T> predicate) {
        List<T> list = nodeList.stream().filter(it -> {
            return predicate.test(it);
        }).collect(Collectors.toList());
        list.forEach(it -> {
            it.setChildren(filterTree(it.getChildren(), predicate));
        });
        return list;
    }
}
